//https://leetcode.cn/problems/binary-tree-level-order-traversal/
package codeRandomThoughts.Test102二叉树的层序遍历;

import codeRandomThoughts.utils.TreeNode;

import java.util.*;

//层序遍历二刷
public class Solution2 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<Integer> layer = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();

        Deque<TreeNode> deque = new LinkedList<>();
        if (root != null) {
            deque.offer(root);
        } else {
            return result;
        }

        int npl = 0;//每层结点数量
        while (!deque.isEmpty()) {
            npl = deque.size();
            while (npl > 0) {
                TreeNode node = deque.poll();
                layer.add(node.val);
                if (node.left != null) {
                    deque.offer(node.left);
                }
                if (node.right != null) {
                    deque.offer(node.right);
                }
                npl--;
            }
            result.add(layer);
            layer = new ArrayList<>();
        }
        return result;
    }
}
